<?php

namespace app\admin\controller\basic;

use app\admin\controller\report\OrderProject;
use app\admin\library\Auth;
use app\admin\model\business\OrderAssets;
use app\admin\model\business\StashDetail;
use app\admin\model\report\Finance;
use app\common\controller\Backend;
use app\common\model\Category;
use fast\Pinyin;
use fast\Tree;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;
use think\response\Json;

/**
 * 单位信息管理
 *
 * @icon fa fa-circle-o
 */
class Unit extends Backend
{

    /**
     * Unit模型对象
     * @var \app\admin\model\basic\Unit
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\basic\Unit;

    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function getCategory()
    {

        $data = Category::where('type', 'unit')->select();
        $data = collection($data)->toArray();
        $tree = Tree::instance();
        $tree->init($data);
        $data = $tree->getTreeList($tree->getTreeArray(0));
        return $data;
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //  $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        foreach ($list->items() as &$item) {
            $item['category_id'] = Category::where('id', $item['category_id'])
                ->value('name');
        }

        $result = ['total' => $list->total(), 'rows' => $list->items()];

        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;

        $params['spell'] = Pinyin::get($params['name'], true);

        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $params['spell'] = Pinyin::get($params['name'], true);
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function import()
    {
        $cate = Category::where('type', 'unit')->column('id', 'name');
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    $row['spell'] = Pinyin::get($row['name'], true);
                    $row['category_id'] = $cate[$row['category_id']] ?? 0;
                    $insert[] = $row;
                }
            }

        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        try {
            //是否包含admin_id字段
            $has_admin_id = false;
            foreach ($fieldArr as $name => $key) {
                if ($key == 'admin_id') {
                    $has_admin_id = true;
                    break;
                }
            }
            if ($has_admin_id) {
                $auth = Auth::instance();
                foreach ($insert as &$val) {
                    if (!isset($val['admin_id']) || empty($val['admin_id'])) {
                        $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;

                    }
                }
            }
            $this->model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }

    /**
     * Selectpage的实现方法
     *
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可
     *
     */
    public function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist = $this->model->where($where)
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => $item[$primarykey] ?? '',
                        $field => $item[$field] ?? '',
                    ];
                } else {
                    $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }


    /**
     * Notes: 利润统计
     * User: AerYYY
     * Date: 2/18/24 10:01 AM
     * @return string|Json
     * @throws DbException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function profit()
    {
        //  $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        $filter = json_decode($this->request->get("filter"), true);
        $op = json_decode($this->request->get("op"), true);

        $wh_stash = [];
        $wh_project = [];
        $wh_assets = [];
        if (!empty($filter['date'])) {
            $wh_stash['s.date'] = ['between time', explode(' - ', $filter['date'])];
            $wh_project['date'] = ['between time', explode(' - ', $filter['date'])];
            $wh_assets['date'] = ['between time', explode(' - ', $filter['date'])];

            unset($filter['date']);
            unset($op['date']);
        }
        if (!empty($filter['staff_id'])) {
            $wh_stash['s.staff_id'] = ['eq', $filter['staff_id']];
            $wh_project['staff_id'] = ['eq', $filter['staff_id']];
            $wh_assets['staff_id'] = ['eq', $filter['staff_id']];

            unset($filter['staff_id']);
            unset($op['staff_id']);
        }

        $this->request->get(["filter" => json_encode($filter), 'op' => json_encode($op)]); //重置一下 get 接收参数 ヾ(✿ﾟ▽ﾟ)ノ
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        $sum_sx_amount = 0; // 销售收入
        $sum_project_amount = 0; //项目收入
        $sum_other_amount = 0; //其他收入

        $sum_cost_amount = 0; // 销售成本
        $sum_project_zc_amount = 0; //项目支出
        $sum_other_zc_amount = 0; //其他支出

        foreach ($list->items() as &$item) {
            $item['xs_amount'] = 0; //销售金额
            $item['xs_cost_amount'] = 0; //销售成本金额
            $item['xt_amount'] = 0; //退货金额
            $item['xt_cost_amount'] = 0; //退货成本金额
            $xs_list = StashDetail::alias('s')
                ->join('stash_goods_detail d', 's.order_no = d.order_no')
                ->where('s.unit_id', $item['id'])
                ->where('s.status', 'in', [Finance::STATUS_SH, Finance::STATUS_SHTH])
                ->where($wh_stash)
                ->field('s.id,s.unit_id,s.order_no,d.*')
                ->select();
            if (count($xs_list) > 0) {
                $xs_list = collection($xs_list)->toArray();
                foreach ($xs_list as $value) {
                    if ($value['status'] == Finance::STATUS_SH) {
                        $item['xs_amount'] += $value['amount'];
                        $item['xs_cost_amount'] += $value['cost_amount'];
                    } else {
                        $item['xt_amount'] += $value['amount'];
                        $item['xt_cost_amount'] += $value['cost_amount'];
                    }
                }
            }
            $item['sum_amount'] = bcsub($item['xs_amount'], $item['xt_amount'], 2); //总销售收入
            $item['sum_cost_amount'] = bcsub($item['xs_cost_amount'], $item['xt_cost_amount'], 2); //总销售成本
            $sum_sx_amount += $item['sum_amount'];
            $sum_cost_amount += $item['sum_cost_amount'];

            $project_list = \app\admin\model\business\OrderProject::where('unit_id', $item['id'])
                ->where('status', 'in', [Finance::STATUS_SR, Finance::STATUS_ZC])
                ->where($wh_project)
                ->select();

            $item['project_sr_amount'] = 0; //项目收入
            $item['project_zc_amount'] = 0; //项目支出

            if (count($project_list) > 0) {
                $project_list = collection($project_list)->toArray();
                foreach ($project_list as $value) {
                    if ($value['status'] == Finance::STATUS_SR) {
                        $item['project_sr_amount'] += $value['price'];
                    } else {
                        $item['project_zc_amount'] += $value['price'];
                    }
                }
            }
            $sum_project_amount += $item['project_sr_amount'];
            $sum_project_zc_amount += $item['project_zc_amount'];

            $assets_list = OrderAssets::where('unit_id', $item['id'])
                ->where('status', 'in', [Finance::STATUS_SK, Finance::STATUS_FK])
                ->where($wh_assets)
                ->select();

            $item['other_sr_amount'] = 0; //其他收入
            $item['other_zc_amount'] = 0; //其他支出

            if (count($assets_list) > 0) {
                $assets_list = collection($assets_list)->toArray();
                foreach ($assets_list as $value) {
                    if ($value['status'] == Finance::STATUS_SK) {
                        $item['other_sr_amount'] += $value['price'];
                    } else {
                        $item['other_zc_amount'] += $value['price'];
                    }
                }
            }
            $sum_other_amount += $item['other_sr_amount'];
            $sum_other_zc_amount += $item['other_zc_amount'];
        }

        $income = round($sum_sx_amount + $sum_project_amount + $sum_other_amount, 2);
        $expenditure = round($sum_cost_amount + $sum_project_zc_amount + $sum_other_zc_amount, 2);
        $data = [
            'sum_sx_amount' => round($sum_sx_amount, 2), //销售收入
            'sum_project_amount' => round($sum_project_amount, 2),//项目收入
            'sum_other_amount' => round($sum_other_amount, 2),//其他收入

            'sum_cost_amount' => round($sum_cost_amount, 2), //销售成本支出
            'sum_project_zc_amount' => round($sum_project_zc_amount, 2), //项目支出
            'sum_other_zc_amount' => round($sum_other_zc_amount, 2), //其他支出

            'income' => $income, // 总收入
            'expenditure' => $expenditure, // 总支出
        ];

        $result = ['total' => $list->total(), 'rows' => $list->items(), 'data' => $data];

        return json($result);
    }

    /**
     * Notes: 弃用
     * User: AerYYY
     * Date: 2/18/24 10:24 AM
     * @return string|Json
     * @throws DbException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function refund()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        $filter = json_decode($this->request->get("filter"), true);
        $op = json_decode($this->request->get("op"), true);

        $wh_stash = [];
        $wh_project = [];
        $wh_assets = [];
        if (!empty($filter['date'])) {
            $wh_stash['s.date'] = ['between time', explode(' - ', $filter['date'])];
            $wh_project['date'] = ['between time', explode(' - ', $filter['date'])];
            $wh_assets['date'] = ['between time', explode(' - ', $filter['date'])];

            unset($filter['date']);
            unset($op['date']);
        }
        if (!empty($filter['staff_id'])) {
            $wh_stash['s.staff_id'] = ['eq', $filter['staff_id']];
            $wh_project['staff_id'] = ['eq', $filter['staff_id']];
            $wh_assets['staff_id'] = ['eq', $filter['staff_id']];

            unset($filter['staff_id']);
            unset($op['staff_id']);
        }

        $this->request->get(["filter" => json_encode($filter), 'op' => json_encode($op)]); //重置一下 get 接收参数 ヾ(✿ﾟ▽ﾟ)ノ
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        $assets = \app\admin\model\basic\Assets::field('id,name')->select();
        foreach ($list->items() as &$item) {
            foreach ($assets as $value) {
                $item['assets'] = [
                    'id'
                ];
            }
        }

        $result = ['total' => $list->total(), 'rows' => $list->items(), 'data' => []];
        return json($result);
    }
}
